package com.aiit.shiro;

import com.aiit.pojo.SysUser;
import com.aiit.service.SysPermissionService;
import com.aiit.service.SysRoleService;
import com.aiit.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class CustomRealm2 extends AuthorizingRealm {

    @Autowired
    private SysRoleService  sysRoleService;
    @Autowired
    private SysPermissionService  sysPermissionService;
    //获取用户的权限数据
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) throws UnauthorizedException{
        //能进入到这里，表示账号已经通过验证了
        String userName =(String) principalCollection.getPrimaryPrincipal();
        Set<String> permissions;
        Set<String> roles;
        try{
            //通过service获取角色和权限
            permissions = sysPermissionService.listPermissions(userName);
            roles= sysRoleService.listRoles(userName);
        }catch(Exception e){
          throw new UnauthorizedException();
        }
        //授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        s.setStringPermissions(permissions);
        s.setRoles(roles);
        return s;


    }
    //获取用户的凭证（密码）数据
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) authenticationToken;
        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo("aiit","asfafds",ByteSource.Util.bytes("1096bf61-a1cd-46fb-b089-532e4e9c0d33"),getName());
        return a;

    }
}
